import React, { useState, FC } from 'react';
import Notification from '@/components/Notification';
import Toast from '@/components/Toast';
import './index.less';
import { DOMModal } from '../DOMModal';

/**
 * ------实名认证上传组件说明------
 * defaultBg：默认背景
 * defaultText：文案显示
 * imageMaxSize：上传的最大图片大小限制，如果接口此值为空，默认传1MB，在业务逻辑立面处理
 * imgBase64：上传后的imgBase64格式照片
 * inputDisable：是否可上传
 * disabledClickAction：不可上传时，点击上传组件方法
 * uploadMethod： 上传组件方法
 * uploadDidTrigger：上传完后方法
 */

let photoLoading = 0;
const Upload: FC<any> = (props: any) => {
  const {
    defaultBg,
    defaultText,
    imgBase64,
    isContract,
    inputDisable,
    disabledClickAction,
    uploadMethod,
    uploadDidTrigger,
    clearUploadInfo = false
  } = props;
  const imageMaxSize = props.imageMaxSize || 1;
  const [imgType] = useState('image/jpg,image/jpeg,image/png');

  let onChangeHandle = async (event: any) => {
    let _file = event.target.files[0];
    photoLoading = 0;
    if (!_file) {
      return;
    }
    if (imgType.indexOf(_file.type) < 0) {
      Toast.show('获取照片失败，请上传jpg、png、jpeg格式的图片文件');
      return;
    }

    let formData = new FormData();
    const fileSize = _file.size / 1024;
    if (fileSize > imageMaxSize * 1024) {
      DOMModal.handleOpenModal({
        wrapClassName: 'upload-dialog',
        content: `请上传${imageMaxSize}M以内的照片`
      });
      return;
    }

    formData.append('file', _file);

    const NotificationContent = isContract ? '正在验证' : '上传中';
    Notification.show(NotificationContent + '...', 60);

    uploadMethod(formData).then(
      (res: any) => {
        Notification.show('', 0.01);
        uploadDidTrigger && uploadDidTrigger('success', res);
      },
      (err: any) => {
        Notification.show('', 0.01);
        uploadDidTrigger && uploadDidTrigger('fail', err);
      }
    );
  };
  let onInputClick = (event: any) => {
    event.stopPropagation();
    // 可二次上传同一张图片
    event.target.value = null;
    // 避免连续点击时重复打开相册
    if (photoLoading) {
      event.preventDefault();
    }
    photoLoading = 1;
    setTimeout(function() {
      photoLoading = 0;
    }, 500);
  };

  return (
    <>
      <div className={'upload_component'}>
        {imgBase64 ? (
          // data:image/jpeg;base64, base64前缀编码
          <img src={`${imgBase64}`} alt="" />
        ) : (
          defaultBg
        )}
        {imgBase64 && (
          <div className="mask_bg">
            <img className="mask_bg_img" src={imgBase64} alt="" />
          </div>
        )}
        <form
          className="icon_add_status"
          onClick={() => {
            inputDisable && disabledClickAction();
          }}
        >
          {clearUploadInfo ? null : (
            <>
              <i className="icon-add"></i>
              <div className="upload_message">{defaultText}</div>
            </>
          )}
          {/* accept={
              window['JSSDK'].Client.getOSVersion() === '6.0.1' ? '' : imgType
            } */}
          <input
            accept={imgType}
            type="file"
            id="uploadFile"
            className={`upload_item ${inputDisable ? 'pointer_events' : ''}`}
            disabled={inputDisable}
            onChange={onChangeHandle}
            onClick={onInputClick}
          />
        </form>
      </div>
    </>
  );
};

export default Upload;
